import { createServer } from "node:http";
import fs from "node:fs";
import data from "./index.json" assert { type: "json" };

const hostname = "127.0.0.1";
const port = 8080;

const serve = createServer((req, res) => {
  // res.statusCode = 200;
  // res.setHeader("Content-Type", "text/plain");
  // res.end(
  //   JSON.stringify({
  //     code: 200,
  //     message: "hello wod",
  //   })
  // );
  console.log(data);

  if (req.url === "/" || req.url === "/index.html") {
    // Serve index.html
    fs.readFile("index.html", "utf-8", (err, data) => {
      if (err) {
        console.error(err);
        res.statusCode = 500;
        res.end("Error loading index.html");
        return;
      }
      res.statusCode = 200;
      res.setHeader("Content-Type", "text/html");
      res.setHeader(
        "Content-Security-Policy",
        "script-src 'self'; style-src 'self'"
      );
      res.end(data);
    });
  } else if (req.url === "/index.css") {
    // Serve index.css
    fs.readFile("index.css", "utf-8", (err, data) => {
      if (err) {
        console.error(err);
        res.statusCode = 404;
        res.end("CSS file not found");
        return;
      }
      res.statusCode = 200;
      res.setHeader("Content-Type", "text/css");
      res.end(data);
    });
  } else {
    // Handle other requests (optional)
    res.statusCode = 404;
    res.end("Resource not found");
  }
});

serve.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
